﻿using System;
using System.IO;
using NUnit.Framework;
using StoryQ;
using TripleA.StoryQ;

namespace TripleA.Tests.Database
{
    [TestFixture]
    public class RunScriptTests : BddFeature
    {
        protected override Feature DescribeFeature()
        {
            return new Story("Testing the database runscript extension")
                .InOrderTo("Run sql scripts using sqlcmd.exe")
                .AsA("system test")
                .IWant("triplea to manage this for me");
        }

        [Test]
        public void ExplicitSqlCmdLocationWithValidScript()
        {
            using (var domain = new DatabaseDomain())
            {
                Feature.WithScenario("Running a valid script with an explicit sqlcmd location should work ok")
                    .Given(domain.TheSqlScriptIs_, "valid.sql")
                    .And(domain.TheDefaultSqlCmdExeLocationIsUsed)
                    .When(domain.TheRunScriptStepIsCalled)
                    .Then(domain.ThrewNoException)
                    .ExecuteWithReport();
            }
        }

        [Test]
        public void AppConfigSqlCmdLocationWithValidScript()
        {
            using (var domain = new DatabaseDomain())
            {

                Feature.WithScenario(
                    "Running a valid script using the sqlcmd location stored in appSettings should work ok")
                    .Given(domain.TheSqlScriptIs_, "valid.sql")
                    .And(domain.TheSqlCmdLocationIsDefinedInTheAppSettings)
                    .When(domain.TheRunScriptStepIsCalled)
                    .Then(domain.ThrewNoException)
                    .ExecuteWithReport();
            }
        }

        [Test]
        public void ExplicitSqlCmdLocationWithInvalidScript()
        {
            using (var domain = new DatabaseDomain())
            {
                Feature.WithScenario("Running a invalid script should fail with an exit code mismatch message")
                    .Given(domain.TheSqlScriptIs_, "invalid.sql")
                    .And(domain.TheDefaultSqlCmdExeLocationIsUsed)
                    .When(domain.TheRunScriptStepIsCalled)
                    .Then(domain.ShouldThrow_Exception, typeof(AggregateException))
                    .And(domain.TheMessageForException_Contains_, 0, "Process sqlcmd.exe exited with code ")
                    .And(domain.TheMessageForException_Contains_, 0, "Output from sqlcmd.exe ")
                    .And(domain.TheMessageForException_Contains_, 0, "Incorrect syntax near the keyword 'is'")
                    .ExecuteWithReport();
            }
        }
    }
}